package com.cj.search.service.Impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.cj.common.clients.ItemClient;
import com.cj.common.dto.Item;
import com.cj.common.dto.PageDTO;
import com.cj.search.pojo.ItemDoc;
import com.cj.search.pojo.RequestParams;
import com.cj.search.service.ISearchService;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author Hasee
 * @version 1.0
 * @description: TODO
 * @date 2023/3/18 20:09
 */
@Service
public class SearchService implements ISearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private ItemClient itemClient;
    @Override
    public List<String> getSuggestion(String prefix){
        try {
            SearchRequest request = new SearchRequest("item");
            request.source().fetchSource(new String[0],null);

            request.source().suggest(new SuggestBuilder()
                    .addSuggestion("my_suggestion", SuggestBuilders
                            .completionSuggestion("suggestion")
                            .size(10)
                            .skipDuplicates(true)
                            .prefix(prefix)));
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            CompletionSuggestion suggestion = search.getSuggest().getSuggestion("my_suggestion");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().string());

            }


            return list;
        }catch (IOException e){
            throw new RuntimeException(e);
        }

    }

    @Override
    public Map<String, List<String>> filter(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("item");
            request.source().size(0);
            requestQuery(request,requestParams);

            request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(10));
            request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(10));
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            Map<String, List<String>> map = new HashMap<>(2);
            Aggregations aggregations = response.getAggregations();

            Terms brandAgg = aggregations.get("brandAgg");
            List<String> brandList = new ArrayList<>();
            for (Terms.Bucket bucket : brandAgg.getBuckets()) {
                String key = bucket.getKeyAsString();
                brandList.add(key);
            }
            map.put("brand", brandList);

            Terms categoryAgg = aggregations.get("categoryAgg");
            List<String> categoryList = new ArrayList<>();
            for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
                String key = bucket.getKeyAsString();
                categoryList.add(key);
            }
            map.put("category", categoryList);

            return map;
        } catch (IOException e) {
           throw  new RuntimeException(e);
        }
    }

    @Override
    public PageDTO<ItemDoc> list(RequestParams requestParams) {
        try {
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            SearchRequest request = new SearchRequest("item");

            requestQuery(request,requestParams);
            request.source().from((page - 1) * size).size(size);

            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long value = hits.getTotalHits().value;
            SearchHit[] hits1 = hits.getHits();
            List<ItemDoc> list = new ArrayList<>();
            for (SearchHit documentFields : hits1) {
                String source = documentFields.getSourceAsString();
                ItemDoc itemDoc = MAPPER.readValue(source, ItemDoc.class);
                list.add(itemDoc);
            }


            return new PageDTO<>(value,list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            Item item = itemClient.query(id);
            ItemDoc itemDoc = new ItemDoc(item);
            IndexRequest request = new IndexRequest("item").id(id.toString());

            request.source(MAPPER.writeValueAsString(itemDoc), XContentType.JSON);

            restHighLevelClient.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("item", id.toString());
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void requestQuery(SearchRequest request, RequestParams requestParams) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        String key = requestParams.getKey();
        if (StringUtils.isNotBlank(key)) {

            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {

            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        String brand = requestParams.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }

        String category = requestParams.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }

        Long minPrice = requestParams.getMinPrice();
        Long maxPrice = requestParams.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100).lte(maxPrice * 100));
        }

        request.source().query(boolQuery);
    }

}
